package htmodels

import (
	"github.com/astaxie/beego/orm"
	"anfang/models"
)
func HTUsersAdd(users *models.Users) error {
	o := orm.NewOrm()
	_, err := o.Insert(users)
	return err
}

func HTUsersGetDetail(users *models.Users) error {
	o := orm.NewOrm()
	return o.Read(users)
}

func HTUsersGetCount(search string, searchFiled string , UserType int) (int64, error) {
	o := orm.NewOrm()
	m := models.Users{}
	count, err := o.QueryTable(m.TableName()).Filter(m.FN_UserType(), UserType).Filter(searchFiled + "__icontains", search).Count()
	return count, err
}

func HTUsersGetList(userss *[]models.Users, fields []string , UserType int, offset int64, limit int, search string, searchFiled string, orderby string) error {
	o := orm.NewOrm()
	m := models.Users{}
	_, err := o.QueryTable(m.TableName()).Filter(m.FN_UserType(), UserType).Filter(searchFiled + "__icontains", search).OrderBy(orderby).Offset(offset).Limit(limit).All(userss, fields...)
	return err
}

func HTUsersDelete(Ids []int64) (int64, error) {
	o := orm.NewOrm()
	m := models.Users{}
	count, err := o.QueryTable(m.TableName()).Filter("Id" + "__in", Ids).Delete()
	return count, err
}
func HTUsersUpdate(users *models.Users) error {
	o := orm.NewOrm()
	_, err := o.Update(users)
	return err
}

//return true if pass and name(phone) right
func HTCheckUserLogin(m *models.Users, user string, pass string, emailOrPhone bool) bool {
	o := orm.NewOrm()
	querybuilder := o.QueryTable(m.TableName())
	if emailOrPhone {
		querybuilder = querybuilder.Filter(m.FN_Email(), user)
	} else {
		querybuilder = querybuilder.Filter(m.FN_Phone(), user)
	}
	if err := querybuilder.One(m); err != nil {
		return false
	}
	if pass != m.Password {
		return false
	}
	return true
}
